<?php

namespace App\Admin\Controllers;

use App\Miya\Models\Section;
use App\Miya\Tools\TagTool;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Validation\Rule;
use Overtrue\Pinyin\Pinyin;

class SectionController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '内容区块管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Section());

        $grid->column('id', '序号');
        $grid->column('name', '区块名称')->label();
        $grid->column('tag', '标签')->label();
        $grid->column('content', '区块内容')->view('miya::sections._content');

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Section());

        $form->tab('基础设置', function (Form $form) {
            $form->text('name', '区块名称');
            $form->UEditor('content', '内容');
        })->tab('高级设置', function (Form $form) {
            if ($form->isCreating()) {
                $form->text('tag', '标签')->rules([Rule::unique('sections')]);
            } elseif ($form->isEditing()) {
                $section = Section::find(request()->route('section'));
                $form->text('tag', '标签')->rules([Rule::unique('sections')->ignore($section)]);
            }
        });

        $form->saving(function (Form $form) {
            if (!$form->tag) {
                $form->tag = TagTool::makeTag($form->name, config('miya.tag_suffix.section'));
            }
        });
        return $form;
    }
}
